// import { defineStore } from 'pinia'
// import { ref } from 'vue'

// export const useUserStore = defineStore('user', () => {
//   // 安全获取 token
//   const token = ref('')
//   try {
//     const storedToken = localStorage.getItem('token')
//     token.value = storedToken ? String(storedToken) : ''
//   } catch (error) {
//     console.error('读取 token 失败:', error)
//   }

//   // 安全解析用户信息
//   const initialUser = () => {
//     try {
//       const storedUser = localStorage.getItem('user')
//       if (!storedUser || storedUser === 'undefined') return null
//       return JSON.parse(storedUser)
//     } catch (error) {
//       console.error('解析用户信息失败:', error)
//       localStorage.removeItem('user') // 自动清理损坏数据
//       return null
//     }
//   }

//   const userInfo = ref(initialUser() || {}) // 确保 userInfo 默认是对象
//   const role = ref(userInfo.value?.role || '用户') // 确保 role 不为空

//   // 登录操作（优化 userData 处理）
//   const login = (newToken, userData = {}) => {
//     console.log("接收到的用户数据:", newToken, userData); // ✅ 调试日志
  
//     if (!newToken || typeof newToken !== "string") {
//       console.warn("token 不是字符串，尝试转换为字符串:", newToken);
//       newToken = String(newToken || ""); // 防止 token 为空
//     }
  
//     if (!userData || typeof userData !== "object") {
//       console.error("用户数据无效:", userData);
//       throw new Error("用户数据必须是对象");
//     }
  
//     if (!userData.role) {
//       console.warn("用户数据缺少 role 字段，设置默认值 'guest'");
//       userData.role = "guest";
//     }
  
//     token.value = newToken;
//     userInfo.value = userData;
//     role.value = userData.role;
  
//     localStorage.setItem("token", newToken);
//     localStorage.setItem("user", JSON.stringify(userData));
//   };
  
//   // 退出登录
//   const logout = () => {
//     console.log('用户登出')

//     // 清除状态
//     token.value = ''
//     userInfo.value = {}
//     role.value = '用户'

//     // 清除存储
//     try {
//       localStorage.removeItem('token')
//       localStorage.removeItem('user')
//       sessionStorage.clear() // 彻底清理 session 数据
//     } catch (error) {
//       console.error('清理存储失败:', error)
//     }
//   }

//   return { token, userInfo, role, login, logout }
// })
// store/auth.js
// store/auth.js
// src/store/auth.js
// src/store/auth.js
// src/store/auth.js
// src/store/auth.js
// src/stores/userStore.js
// src/stores/userStore.js
// src/stores/userStore.js
// src/stores/userStore.js
// src/stores/userStore.js
// src/stores/userStore.js
// src/stores/userStore.js
// src/stores/userStore.js
// src/stores/userStore.js
// src/stores/userStore.js
// src/stores/userStore.js
// src/stores/userStore.js
// src/stores/userStore.js
import { defineStore } from 'pinia';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    logins: JSON.parse(localStorage.getItem('logins') || '[]'),
    activeUsers: [],
    pageUsers: {},
  }),
  actions: {
    login(token, user, pageKey) {
      const loginInfo = { token, username: user.userName, id: user.id, role: user.role };
      const existing = this.logins.find(l => l.username === user.userName);
      if (existing) {
        existing.token = token;
        existing.id = user.id;
      } else {
        this.logins.push(loginInfo);
      }
      this.activeUsers = [loginInfo]; // 当前会话只记录当前用户
      this.pageUsers[pageKey] = user.userName; // 明确设置 pageKey 对应的用户名
      this.saveToLocalStorage();
      sessionStorage.setItem('pageKey', pageKey); // 保存当前标签页的 pageKey
      sessionStorage.setItem(`pageUsers-${pageKey}`, user.userName); // 同步到 sessionStorage
      console.log('登录后 logins:', this.logins);
      console.log('登录后 activeUsers:', this.activeUsers);
      console.log('登录后 pageUsers:', this.pageUsers);
    },
    switchPageUser(pageKey, username) {
      this.pageUsers[pageKey] = username;
      sessionStorage.setItem(`pageUsers-${pageKey}`, username);
    },
    logout(pageKey) {
      const username = this.pageUsers[pageKey];
      if (username) {
        this.activeUsers = [];
        delete this.pageUsers[pageKey];
        sessionStorage.removeItem(`pageUsers-${pageKey}`);
        sessionStorage.removeItem('pageKey');
        this.saveToLocalStorage();
      }
    },
    getToken(pageKey) {
      const username = this.pageUsers[pageKey];
      const user = this.activeUsers.find(u => u.username === username) || this.logins.find(l => l.username === username);
      return user?.token || '';
    },
    saveToLocalStorage() {
      localStorage.setItem('logins', JSON.stringify(this.logins));
    },
    initialize() {
      const storedLogins = JSON.parse(localStorage.getItem('logins') || '[]');
      this.logins = storedLogins;
      const storedPageKey = sessionStorage.getItem('pageKey');
      if (storedPageKey) {
        const storedUsername = sessionStorage.getItem(`pageUsers-${storedPageKey}`);
        if (storedUsername) {
          this.pageUsers[storedPageKey] = storedUsername;
          const user = this.logins.find(l => l.username === storedUsername);
          if (user) {
            this.activeUsers = [user];
          }
        }
      }
    },
    getActiveUser(pageKey) {
      const username = this.pageUsers[pageKey];
      const user = this.activeUsers.find(user => user.username === username) || this.logins.find(login => login.username === username);
      return user;
    },
  },
});